package com.jxsd.edu.cn.tools;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


public class IPCatcher {

	/**
	 * 通过有道服务获取用户ip所在位置
	 * @return inputStream
	 */
	public InputStream youdaoIPService(String  ip) throws Exception {
		String netPath = "http://www.youdao.com/smartresult-xml/search.s?type=ip&q="+ip;
		URL url = new URL(netPath);
		HttpURLConnection connection = (HttpURLConnection) url.openConnection();
		return connection.getInputStream();
	}

	
	/**
	 * 将InputStream转换为字符串
	 */
	public String InputStreamToString(InputStream inputStream) throws Exception{
		String allIPData="";
		String str;
		BufferedReader  br=new BufferedReader(new InputStreamReader(inputStream, "GBK"));
		str=br.readLine();
		while(str!=null){
			str=br.readLine();
			if(str!=null){
				allIPData=allIPData+str;
			}
		}
		inputStream.close();
		return allIPData;
	}
	
	/**
	 * 开始进行location进行匹配
	 * @param str
	 * @return
	 */
	public String getContext(String str) {
        String result = null;
        Pattern p = Pattern.compile("<location>([^</location>]*)");//匹配<location>开头，</location>结尾的文档
        Matcher m = p.matcher(str );//开始编译
        while (m.find()) {
            result=(m.group(1));//获取被匹配的部分
        }
        return result;
    }
	
	/**
	 * 获取城市
	 * */
	public  String  getCity(String ip)  throws  Exception
	{
		InputStream  in=null;
		String s=null;
		String  location=null;

		System.out.println("ip:"+ip);
		in=youdaoIPService(ip);
		s=InputStreamToString(in);
		location=getContext(s);
		System.out.println("location:"+location);
		
		if(null==location)
		{
			return  "";
		}
		
		String  city=null;
		int  begin=location.indexOf("省");
		int  end=location.indexOf("市");
		if(begin<=0||end<=0)
	    	{
			  return  "";
		   }
		else
		  city=location.substring(begin+1, end);
		System.out.println("city:"+city);
		return  city;
	}
}
